package services

import (
	"context"

	"boomlive.com/boomlive-common/utils"
	"boomlive.com/boomlive-openapi-game/models"
	"github.com/beego/beego/v2/core/logs"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

// CheckToken 验证传入的 token 是否和 Mongo 中的 token 一致
func CheckToken(userID int64, token string) bool {
	// 创建 AnchorInfo，用于查询真实 token
	anchor := &models.AnchorInfo{
		AnchorId: userID,
		Token:    token,
	}

	var u models.UserToken
	client := utils.GetMongoClient()

	col := client.Database("db_oauth").Collection("user_atok")
	filter := bson.M{"user_id": anchor.AnchorId, "token": token}

	err1 := col.FindOne(context.TODO(), filter).Decode(&u)
	if err1 != nil {
		logs.Info("test getUserToken err1: ", err1.Error())
		if err1 != mongo.ErrNoDocuments {
			logs.Info("test getUserToken err1: ", err1.Error())
		}
	}

	logs.Info("getUserToken UserId: ", u.UserId, ", Token: ", u.Token)
	if u.Token == token {
		return true
	}

	logs.Error("CheckToken: token 不匹配, userID=%d, input=%s", userID, token)
	return false
}
